import 'dart:convert';
import 'package:xml/xml.dart';

///被适配类
class TargetAdapter {
  String? name;

  TargetAdapter({this.name});
}

///规范化结构定义
abstract class ITarget {
  TargetAdapter getTargetAdapterList();
}

///对象适配器
///种类A（json类型的string）
class DataBox {
  static String receivedJsonData = '''
      {
        "name": "data from json"
      }
    ''';
  static String receivedXmlData = '''
      <name>date from xml</name>
    ''';
}

class TypeJsonAdapter extends ITarget {
  var targetAdapter = TargetAdapter();

  @override
  TargetAdapter getTargetAdapterList() {
    final jsonData = json.decode(DataBox.receivedJsonData);
    String name = jsonData["name"];
    targetAdapter.name = name;
    return targetAdapter;
  }
}

///种类B（xml类型的string）
class TypeXmlAdapter extends ITarget {
  var targetAdapter = TargetAdapter();

  @override
  TargetAdapter getTargetAdapterList() {
    XmlDocument xmlDocument = XmlDocument.parse(DataBox.receivedXmlData);
    String text = xmlDocument.getElement("name")!.text;
    targetAdapter.name = text;
    return targetAdapter;
  }
}

///客户端调用
class Client {
  late ITarget iTarget;

  Client({required this.iTarget});

  getString() {
    final result = iTarget.getTargetAdapterList();
    print(result.name);
  }
}

main() {
  Client clientJson = Client(iTarget: TypeJsonAdapter());
  Client clientXml = Client(iTarget: TypeXmlAdapter());
  clientJson.getString(); //data from json
  clientXml.getString(); //date from xml
}
